package com.yt.sys.api.client;

import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.db.utils.RedisTokenUtil;
import com.yt.sys.models.bo.LoginInfoSaveBO;
import com.yt.sys.models.service.ILoginInfoService;
import com.yt.sys.models.vo.LoginInfoVO;
import com.yt.sys.models.vo.SysPermissionVO;
import com.yt.sys.models.vo.SysUserVO;
import com.yt.sys.service.SysUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 用户登录信息控制器
 *
 * @author zhou
 * @Date 2025-09-03 15:54:44
 */

@RestController
@RequestMapping("/api/loginInfo")
@Slf4j
@Api(value = "LoginInfoApiController", tags = "用户登录信息Api接口")
public class LoginInfoApiController {

    @DubboReference
    private ILoginInfoService loginInfoService;
    @Autowired
    private RedisTokenUtil redisTokenUtil;
    @Resource
    private SysUserServiceImpl sysUserService;
    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping(value = "/login")
    public Result<HashMap<String, Object>> login(@RequestBody LoginInfoSaveBO saveBO) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (saveBO == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        //用户判断账号是否存在，
        LoginInfoVO userLoginVO = loginInfoService.getLogin(saveBO);
        if (userLoginVO == null) {
            return new Result<>(CodeEnum.FAIL_USER_200003);
        }
        //如果存在就判断他密码是否正确
        SysUserVO sysUserVO = loginInfoService.getSysLogin(saveBO);
        if (sysUserVO == null) {
            return new Result<>(CodeEnum.FAIL_USER_200006);
        }

        //生成Token并存入到Redis
        String token = redisTokenUtil.generateToken(sysUserVO.getUserName());
        sysUserVO.setToken(token);

        //返回用户权限信息
        List<SysPermissionVO> permissionVOList = sysUserService.queryPermission(sysUserVO.getId());
        sysUserVO.setPermissionsList(permissionVOList);

        map.put("sysUserVO", sysUserVO);
        return new Result<>(map);

    }
}
